<script setup>
import { ref, onMounted } from "vue";
import { useUserStore } from "@/stores/modules/user";
import CustomTabBar from "@/components/CustomTabBar.vue";

const userStore = useUserStore();

// 用户信息
const userInfo = ref({
  nickname: "",
  avatar: "",
  realName: "",
  description: "",
});

// 统计数据
const stats = ref({
  collect: 0,
  browse: 0,
  interview: 0,
  position: 0,
});

// 下拉刷新状态
const refreshing = ref(false);

// 获取用户信息
const getUserInfo = () => {
  const user = userStore.userInfo;
  if (user) {
    userInfo.value = {
      nickname: user.nickName || user.realName || "用户",
      face: user.face || "/static/images/avatar.png",
      realName: user.realName || user.nickName || "用户",
      description: user.description || "这家公司很优秀，期待您的加入~",
    };
  }
};

// 跳转到设置页面
const goToSettings = () => {
  uni.navigateTo({
    url: "/pages/settings",
  });
};

// 跳转到个人信息编辑页面
const goToEditProfile = () => {
  uni.navigateTo({
    url: "/pages/company/hrEdit/editProfile",
  });
};

// 跳转到企业主页
const goToCompanyHome = () => {
  uni.navigateTo({
    url: "/pages/company/companyHome",
  });
};

// 跳转到我的主页
const goToMyHome = () => {
  uni.navigateTo({
    url: "/pages/company/hrInfo/myHome",
  });
};

// 切换到求职者角色
const switchToCandidate = () => {
  uni.showModal({
    title: "角色切换",
    content: `您当前是招聘者角色，是否要切换到求职者角色？`,
    success: (res) => {
      if (res.confirm) {
        userStore.setUserRole("candidate");
        uni.showToast({
          title: "已切换到求职者",
          duration: 1500,
        });
        setTimeout(() => {
          uni.redirectTo({
            url: "/pages/candidate/position/position",
          });
        }, 1500);
      }
    },
  });
};

// 跳转到我的收藏页面
const goToMyCollections = () => {
  uni.navigateTo({
    url: "/pages/company/recommend/myCollections",
  });
};

// 获取所有统计数据（并行执行）
const getAllStats = () => {
  // 并行获取四个统计数据，不等待，各自更新
  
  // 获取收藏数量
  getHrCollectedResumeCount()
    .then(count => {
      stats.value.collect = count || 0;
    })
    .catch(error => {
      console.error("获取收藏数量失败:", error);
      stats.value.collect = 0;
    });
  
  // 获取浏览数量
  getHrViewRecordCount()
    .then(count => {
      stats.value.browse = count || 0;
    })
    .catch(error => {
      console.error("获取浏览数量失败:", error);
      stats.value.browse = 0;
    });
  
  // 获取职位数量
  getAllJobCountApi()
    .then(count => {
      stats.value.position = count || 0;
    })
    .catch(error => {
      console.error("获取职位数量失败:", error);
      stats.value.position = 0;
    });
  
  // 获取面试数量
  getHrInterviewCountApi()
    .then(count => {
      stats.value.interview = count || 0;
    })
    .catch(error => {
      console.error("获取面试数量失败:", error);
      stats.value.interview = 0;
    });
};

// 跳转到我的浏览记录页面
const goToMyViewHistory = () => {
  uni.navigateTo({
    url: "/pages/company/recommend/viewHistory",
  });
};

// 跳转到职位页面
const goToPositionPage = () => {
  uni.navigateTo({
    url: "/pages/company/position/position"
  });
};

// 跳转到面试列表页面
const goToInterviewList = () => {
  uni.navigateTo({
    url: "/pages/company/interview/interviewList",
  });
};

// 导入API
import { scanQrcodeApi, confirmLoginApi } from "@/api/company.js";
import { getHrCollectedResumeCount, getHrViewRecordCount } from "@/api/resume.js";
import { getAllJobCountApi } from "@/api/position.js";
import { getHrInterviewCountApi } from "@/api/chat.js";

// 扫描QR码
const scanQRCode = () => {
  // #ifdef H5
  // H5环境下使用文件上传方式扫描二维码
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "image/*";
  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (file) {
      try {
        // 使用FileReader读取图片
        const imageUrl = URL.createObjectURL(file);

        // 使用本地jsQR库
        if (!window.jsQR) {
          // 如果jsQR还没有加载，则动态加载本地文件
          const script = document.createElement("script");
          script.src = "/static/js/jsQR.js";
          document.head.appendChild(script);

          await new Promise((resolve) => {
            script.onload = resolve;
          });
        }

        // 创建canvas来解析二维码
        const img = new Image();
        img.onload = async () => {
          const canvas = document.createElement("canvas");
          const ctx = canvas.getContext("2d");
          canvas.width = img.width;
          canvas.height = img.height;
          ctx.drawImage(img, 0, 0);

          const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

          try {
            const code = jsQR(
              imageData.data,
              imageData.width,
              imageData.height
            );
            if (code) {
              const qrToken = code.data;
              console.log("H5扫描结果：", qrToken);

              // 调用扫码API
              await handleScanLogin(qrToken);
            } else {
              uni.showModal({
                title: "扫描失败",
                content: "未检测到二维码，请确保图片清晰",
                showCancel: false,
              });
            }
          } catch (error) {
            console.error("二维码解析错误：", error);
            uni.showModal({
              title: "扫描失败",
              content: "二维码解析失败，请重试",
              showCancel: false,
            });
          }

          URL.revokeObjectURL(imageUrl);
        };

        img.onerror = () => {
          uni.showModal({
            title: "错误",
            content: "图片加载失败",
            showCancel: false,
          });
        };

        img.src = imageUrl;
      } catch (error) {
        console.error("H5扫码错误：", error);
        uni.showModal({
          title: "扫描失败",
          content: "扫描失败，请重试",
          showCancel: false,
        });
      }
    }
  };
  input.click();
  // #endif

  // #ifndef H5
  // 非H5环境使用uni.scanCode
  uni.scanCode({
    onlyFromCamera: false,
    scanType: ["qrCode", "barCode"],
    success: async (res) => {
      const qrToken = res.result;
      console.log("扫描结果：", qrToken);

      // 调用扫码API
      await handleScanLogin(qrToken);
    },
    fail: (err) => {
      console.log("扫描失败：", err);
      uni.showToast({
        title: "扫描失败，请重试",
        icon: "none",
        duration: 2000,
      });
    },
  });
  // #endif
};

// 处理扫码登录流程
const handleScanLogin = async (qrToken) => {
  try {
    uni.showLoading({
      title: "处理中...",
      mask: true,
    });

    // 1. 调用扫码API获取preToken
    const preToken = await scanQrcodeApi(qrToken);
    console.log("扫码API返回preToken：", preToken);

    // 2. 显示确认登录对话框
    uni.hideLoading();

    uni.showModal({
      title: "确认登录",
      content: "是否确认在web端进行登录？",
      success: async (res) => {
        if (res.confirm) {
          try {
            uni.showLoading({
              title: "确认登录中...",
              mask: true,
            });

            // 获取用户ID（从userStore中获取）
            const userId = userStore.userInfo?.id || "";

            if (!userId) {
              uni.hideLoading();
              uni.showToast({
                title: "用户ID获取失败",
                icon: "none",
              });
              return;
            }

            // 3. 调用确认登录API
            const confirmData = {
              qrToken,
              preToken,
              userId,
            };

            await confirmLoginApi(confirmData);
            console.log("确认登录成功");

            uni.hideLoading();
            uni.showToast({
              title: "登录成功",
              icon: "success",
              duration: 2000,
            });
          } catch (error) {
            uni.hideLoading();
            console.error("确认登录错误：", error);
            uni.showModal({
              title: "登录失败",
              content: "网络错误，请重试",
              showCancel: false,
            });
          }
        }
      },
    });

    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.error("扫码登录错误：", error);
    uni.showModal({
      title: "扫码失败",
      content: "网络错误，请重试",
      showCancel: false,
    });
  }
};

onMounted(async () => {
  try {
    // 先获取用户信息
    await userStore.getUserInfoAction();
    getUserInfo();
    getAllStats(); // 并行获取所有统计数据
  } catch (error) {
    console.error("获取用户信息失败:", error);
    // 即使获取用户信息失败，也要显示页面
    getUserInfo();
    getAllStats();
  }
});

// 下拉刷新处理函数
const onPullDownRefresh = async () => {
  try {
    // 设置刷新状态
    refreshing.value = true;

    // 调用store中的getUserInfoAction获取最新用户信息
    await userStore.getUserInfoAction();

    // 更新本地用户信息显示
    getUserInfo();

    // 更新所有统计数据
    getAllStats();

    // 显示成功提示
    uni.showToast({
      title: "刷新成功",
      icon: "success",
      duration: 1500,
    });
  } catch (error) {
    console.error("下拉刷新失败:", error);

    // 显示错误提示
    uni.showToast({
      title: "刷新失败，请重试",
      icon: "none",
      duration: 2000,
    });
  } finally {
    // 延迟关闭刷新状态，确保动画效果
    setTimeout(() => {
      refreshing.value = false;
    }, 500);
  }
};
</script>

<template>
  <view class="page">
    <!-- 上部分 - 蓝色背景区域 -->
    <view class="top-section">
      <!-- 设置按钮 -->
      <view class="options">
        <image
          src="/static/icons/icon-scan.png"
          class="scan-icon"
          @tap="scanQRCode"
        ></image>
        <image
          src="/static/icons/settings.png"
          class="settings-icon"
          @tap="goToSettings"
        ></image>
      </view>

      <!-- 头像和昵称 -->
      <view class="real-me">
        <image :src="userInfo.face" class="my-face"></image>

        <view class="my-name-wrapper">
          <view class="my-name-box">
            <text class="my-name">{{ userInfo.nickname }}</text>
          </view>
          <view class="edit-wrapper">
            <image src="/static/icons/icon-edit.png" class="icon-edit"></image>
            <text class="edit-my-resume">企业信息</text>
          </view>
        </view>
      </view>

      <!-- 4个数字统计 -->
      <view class="numbers">
        <view class="num-item" @tap="goToMyCollections">
          <text class="num-counts">{{ stats.collect }}</text>
          <text class="num-text">收藏</text>
        </view>

        <view class="num-item" @tap="goToMyViewHistory">
          <text class="num-counts">{{ stats.browse }}</text>
          <text class="num-text">浏览</text>
        </view>

        <view class="num-item" @tap="goToInterviewList">
          <text class="num-counts">{{ stats.interview }}</text>
          <text class="num-text">面试</text>
        </view>

        <view class="num-item" @tap="goToPositionPage">
          <text class="num-counts">{{ stats.position }}</text>
          <text class="num-text">职位</text>
        </view>
      </view>

      <!-- VIP升级区域 -->
      <view class="vip-upgrade-box">
        <view class="vip-content">
          <image src="/static/icons/company/VIP.png" class="vip-icon"></image>
          <text class="vip-text">开通VIP享受更多超值权益</text>
          <button class="upgrade-btn">立即升级</button>
        </view>
      </view>
    </view>

    <!-- 下部分 - 白色背景区域 -->
    <view class="bottom-section">
      <!-- 第一个功能box -->
      <view class="block-one">
        <view class="block-box">
          <view class="block-line" @tap="goToEditProfile">
            <view class="left-part">
              <image src="/static/icons/account.png" class="block-icon"></image>
              <text class="left-part-words">个人信息</text>
            </view>

            <view class="right-part">
              <text class="right-part-words" style="color: #31b9b3"
                >修改个人资料</text
              >
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="goToMyHome">
            <view class="left-part">
              <image
                src="/static/icons/company/my_page.png"
                class="block-icon"
              ></image>
              <text class="left-part-words">我的主页</text>
            </view>

            <view class="right-part">
              <text class="right-part-words" style="color: #31b9b3"
                >个性页面展示</text
              >
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="goToCompanyHome">
            <view class="left-part">
              <image
                src="/static/icons/company/company.png"
                class="block-icon"
              ></image>
              <text class="left-part-words">企业主页</text>
            </view>

            <view class="right-part">
              <text class="right-part-words" style="color: #31b9b3"
                >展示企业形象</text
              >
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="switchToCandidate">
            <view class="left-part">
              <image
                src="/static/icons/company/apply.png"
                class="block-icon"
              ></image>
              <text class="left-part-words">我要求职</text>
            </view>

            <view class="right-part">
              <text class="right-part-words" style="color: #31b9b3"
                >切换到求职者</text
              >
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 第二个功能box -->
      <view class="block-two">
        <view class="block-box">
          <view class="block-line">
            <view class="left-part">
              <image src="/static/icons/privacy.png" class="block-icon"></image>
              <text class="left-part-words">隐私规则</text>
            </view>

            <view class="right-part">
              <text class="right-part-words">规则明示</text>
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line">
            <view class="left-part">
              <image src="/static/icons/aboutus.png" class="block-icon"></image>
              <text class="left-part-words">关于我们</text>
            </view>

            <view class="right-part">
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>

          <view class="block-line" @tap="goToSettings">
            <view class="left-part">
              <image
                src="/static/icons/settings2.png"
                class="block-icon"
              ></image>
              <text class="left-part-words">设置</text>
            </view>

            <view class="right-part">
              <image
                src="/static/icons/right-arrow.png"
                class="arrow-icon"
              ></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <CustomTabBar :currentIndex="3" />
  </view>
</template>

<style scoped>
/* 强制覆盖uni-app页面容器的背景色，确保整个页面都是蓝色 */
:deep(.uni-page-body) {
  background-color: #00bdb4 !important;
}

:deep(.uni-page) {
  background-color: #00bdb4 !important;
}

:deep(.uni-page-wrapper) {
  background-color: #00bdb4 !important;
}

.page {
  display: flex;
  flex-direction: column;
  background-color: #00bdb4;
  min-height: 100vh;
}

/* 上部分 - 蓝色背景区域 */
.top-section {
  background-color: #00bdb4;
  padding-top: 32px; /* 为状态栏留出空间 */
  position: relative;
}

.options {
  margin-top: 0;
  margin-right: 20px;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.settings-icon {
  width: 44rpx;
  height: 44rpx;
}

.scan-icon {
  width: 44rpx;
  height: 44rpx;
  margin-right: 32rpx;
}

.real-me {
  margin-top: 2px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.my-face {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  margin-left: 40rpx;
}

.my-name-wrapper {
  margin-right: 40rpx;
  color: #ffffff;
  align-self: center;
  width: 55%;
}

.my-name-box {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}

.my-name {
  font-size: 50rpx;
  font-weight: 500;
  color: #ffffff;
}

.edit-wrapper {
  margin-top: 4rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: center;
}

.icon-edit {
  width: 36rpx;
  height: 36rpx;
  margin-right: 12rpx;
  filter: brightness(0) invert(1);
}

.edit-my-resume {
  font-size: 28rpx;
  color: #ffffff;
}

.numbers {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-top: 40rpx;
  margin-bottom: 80rpx; /* 为VIP区域留出空间，避免遮挡 */
}

.num-item {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.num-counts {
  font-size: 38rpx;
  font-weight: 500;
  color: #ffffff;
}

.num-text {
  font-size: 26rpx;
  font-weight: 300;
  color: #a3fdf1;
  margin-top: 4rpx;
}

/* VIP升级区域 */
.vip-upgrade-box {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  position: absolute;
  bottom: -56rpx; /* 让VIP区域一半在蓝色区域，一半在白色区域 */
  left: 0;
  z-index: 10;
}

.vip-content {
  background-color: #292929;
  width: 90%;
  height: 112rpx;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  border-radius: 32rpx;
  padding: 0 32rpx;
  box-sizing: border-box;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.vip-icon {
  width: 48rpx;
  height: 48rpx;
}

.vip-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #f5ad85;
  flex: 1;
  text-align: center;
}

.upgrade-btn {
  background-color: #f5ad85;
  color: #292929;
  font-size: 26rpx;
  font-weight: 500;
  padding: 12rpx 24rpx;
  border-radius: 24rpx;
  border: none;
  line-height: 1;
}

/* 下部分 - 白色背景区域，填充剩余空间 */
.bottom-section {
  flex: 1;
  background-color: #f8f8f8;
  border-radius: 32rpx 32rpx 0 0;
  padding-top: 76rpx; /* 为VIP区域留出空间 */
  padding-bottom: 20rpx;
  min-height: calc(100vh - 258px - 32px);
}

.block-one {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-bottom: 60rpx;
}

.block-two {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.block-two .block-box {
  height: 320rpx;
}

.block-box {
  background-color: #ffffff;
  width: 96%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  border-radius: 20rpx;
}

.block-one .block-box {
  width: 98%;
  height: 390rpx;
}

.block-line {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 100rpx;
  align-items: center;
}

.left-part {
  align-self: center;
  margin-left: 32rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.right-part {
  align-self: center;
  margin-right: 24rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.block-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 16rpx;
}

.left-part-words {
  font-size: 32rpx;
  font-weight: 400;
  color: #333333;
}

.right-part-words {
  margin-right: 12rpx;
  font-size: 24rpx;
  font-weight: 300;
  color: gray;
}

.arrow-icon {
  width: 24rpx;
  height: 24rpx;
}
</style>